﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _2.UniversalStaticSumMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Test3();
        }

        public delegate double OneArgumentFunction(int i);

        public static double Sum(OneArgumentFunction function)
        {
            double precision = 0.000001;

            double sum = 0;
            double increment = function(1);

            for (int i = 1; Math.Abs(increment) >= precision; i++, increment = function(i))
			{
                sum += increment;
			}

            return sum;
        }

        static void Test1()
        {
            OneArgumentFunction f = (i) => 1.0/(1 << (i - 1));

            double result = Sum(f);

            Console.WriteLine(result);
        }

        static void Test2()
        {
            OneArgumentFunction factorial = null; 
            factorial = (i) => i == 0 ? 1 : i * factorial(i - 1);

            OneArgumentFunction f = (i) => 1.0 / factorial(i);

            double result = Sum(f);

            Console.WriteLine(result);
        }

        static void Test3()
        {
            OneArgumentFunction sign = (i) => i % 2 == 0 ? 1 : -1;
            OneArgumentFunction f = (i) => i==1 ? 1 : 1.0 / (1 << (i - 1)) * sign(i);

            double result = Sum(f);

            Console.WriteLine(result);
        }
    }
}
